package org.abratuhi.kvngroupware.chat.model;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Element;

public class Chatroom {
	
	String id = new String();
	String theme = new String();
	ArrayList<String> members = new ArrayList<String>();
	ArrayList<String> messages = new ArrayList<String>();
	
	public Chatroom(){
		
	}
	public Chatroom(String id, String theme){
		setId(id);
		setTheme(theme);
	}
	
	public String getId(){
		return this.id;
	}
	public String getTheme(){
		return this.theme;
	}
	
	void setId(String id){
		this.id = id;
	}
	void setTheme(String theme){
		this.theme = theme;
	}
	
	public synchronized String addMember(String id){
		String returnMessage = "";
		if(members.contains(id)){
			returnMessage = "Team already contains member with id:\t"+id+"."+"\n";
		}
		else{
			members.add(id);
		}
		return returnMessage;
	}
	
	public synchronized String removeMember(String id){
		String returnMessage = "";
		boolean found = false;
		for(int i=0; i<members.size(); i++){
			if(members.get(i).equals(id)){
				members.remove(i);
				found = true;
			}
		}
		if (!found) returnMessage = "Team doesn't contain member with id:\t"+id+"."+"\n";
		return returnMessage;
	}
	
	public synchronized boolean containsMember(String id){
		return members.contains(id);
	}

	public String[] getMemberIdsAsArray(){
		return members.toArray(new String[members.size()]);
	}
	
	public void appendMessage(String message){
		messages.add(message);
	}
	
	public ArrayList<String> getMessages(){
		return messages;
	}
	
	public String getSummary(){
		StringWriter sw = new StringWriter();
		sw.append(getId());
		sw.append("[");
		for(int i=0; i<members.size(); i++){
			sw.append(members.get(i)+" ");
		}
		sw.append("]");
		return sw.toString();
	}
	
	public Element toElement(){
		Element chatroom = new Element("chatroom");
		chatroom.setAttribute("id", getId());
		chatroom.setAttribute("theme", getTheme());
		for(int i=0; i<members.size(); i++){
			Element user = new Element("user");
			user.setText(members.get(i));
			chatroom.addContent(user);
		}
		return chatroom;
	}
	
	@SuppressWarnings("unchecked")
	public static Chatroom fromElement(Element eChatroom){
		Chatroom chatroom = new Chatroom();
		chatroom.setId(eChatroom.getAttributeValue("id"));
		chatroom.setTheme(eChatroom.getAttributeValue("theme"));
		List<Element> eUsers = eChatroom.getChildren("user");
		for(int i=0; i<eUsers.size(); i++){
			chatroom.addMember(eUsers.get(i).getText());
		}
		return chatroom;
	}

}
